<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑制度' : '新增制度'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="system-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="制度名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入制度名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="制度编号" prop="code">
            <el-input
              v-model="formData.code"
              placeholder="请输入制度编号"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="制度类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择制度类型" style="width: 100%">
              <el-option label="管理制度" value="management" />
              <el-option label="技术规范" value="technical" />
              <el-option label="操作规程" value="operation" />
              <el-option label="安全制度" value="safety" />
              <el-option label="质量标准" value="quality" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本号" prop="version">
            <el-input
              v-model="formData.version"
              placeholder="请输入版本号"
              maxlength="20"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="归属部门" prop="department">
            <el-select v-model="formData.department" placeholder="请选择归属部门" style="width: 100%">
              <el-option label="安全管理部" value="安全管理部" />
              <el-option label="技术部" value="技术部" />
              <el-option label="应急管理部" value="应急管理部" />
              <el-option label="设备部" value="设备部" />
              <el-option label="质量部" value="质量部" />
              <el-option label="运营部" value="运营部" />
              <el-option label="综合办公室" value="综合办公室" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="草稿" value="draft" />
              <el-option label="生效中" value="active" />
              <el-option label="已过期" value="expired" />
              <el-option label="已废止" value="abolished" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生效日期" prop="effectiveDate">
            <el-date-picker
              v-model="formData.effectiveDate"
              type="date"
              placeholder="请选择生效日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="失效日期" prop="expiryDate">
            <el-date-picker
              v-model="formData.expiryDate"
              type="date"
              placeholder="请选择失效日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="制定人" prop="creator">
            <el-input
              v-model="formData.creator"
              placeholder="请输入制定人"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核人" prop="reviewer">
            <el-input
              v-model="formData.reviewer"
              placeholder="请输入审核人"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="制度描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入制度描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="制度内容" prop="content">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="8"
          placeholder="请输入制度详细内容"
          maxlength="5000"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="附件上传">
        <el-upload
          ref="uploadRef"
          :file-list="fileList"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :before-upload="beforeUpload"
          :auto-upload="false"
          multiple
          drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 doc/docx/pdf/txt 格式文件，单个文件不超过 10MB
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="关键词">
        <el-tag
          v-for="tag in formData.keywords"
          :key="tag"
          closable
          @close="handleRemoveKeyword(tag)"
          style="margin-right: 8px; margin-bottom: 8px;"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="keywordInputVisible"
          ref="keywordInputRef"
          v-model="keywordInputValue"
          size="small"
          style="width: 120px; margin-right: 8px;"
          @keyup.enter="handleAddKeyword"
          @blur="handleAddKeyword"
        />
        <el-button
          v-else
          size="small"
          @click="showKeywordInput"
        >
          + 添加关键词
        </el-button>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="handleSaveDraft">保存草稿</el-button>
        <el-button type="primary" @click="handleSubmit">
          {{ isEdit ? '更新' : '提交' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'

// Props
interface Props {
  visible: boolean
  systemData?: any
}

const props = withDefaults(defineProps<Props>(), {
  systemData: () => ({})
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 是否编辑模式
const isEdit = computed(() => !!props.systemData?.id)

// 表单引用
const formRef = ref()
const uploadRef = ref()
const keywordInputRef = ref()

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  code: '',
  type: '',
  version: 'V1.0',
  department: '',
  status: 'draft',
  effectiveDate: '',
  expiryDate: '',
  creator: '',
  reviewer: '',
  description: '',
  content: '',
  keywords: [] as string[],
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入制度名称', trigger: 'blur' },
    { min: 2, max: 100, message: '制度名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入制度编号', trigger: 'blur' },
    { pattern: /^[A-Z0-9-]+$/, message: '制度编号只能包含大写字母、数字和连字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择制度类型', trigger: 'change' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择归属部门', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  creator: [
    { required: true, message: '请输入制定人', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入制度描述', trigger: 'blur' },
    { max: 500, message: '描述不能超过 500 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入制度内容', trigger: 'blur' },
    { min: 10, message: '制度内容至少 10 个字符', trigger: 'blur' }
  ]
}

// 文件列表
const fileList = ref([])

// 关键词输入
const keywordInputVisible = ref(false)
const keywordInputValue = ref('')

// 监听系统数据变化
watch(() => props.systemData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    Object.assign(formData, {
      ...newData,
      keywords: newData.keywords || []
    })
  }
}, { immediate: true, deep: true })

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: '',
    name: '',
    code: '',
    type: '',
    version: 'V1.0',
    department: '',
    status: 'draft',
    effectiveDate: '',
    expiryDate: '',
    creator: '',
    reviewer: '',
    description: '',
    content: '',
    keywords: [],
    remark: ''
  })
  fileList.value = []
  formRef.value?.clearValidate()
}

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (visible && !isEdit.value) {
    resetForm()
  }
})

// 文件变化处理
const handleFileChange = (file: any, fileList: any[]) => {
  // 处理文件变化
}

// 文件移除处理
const handleFileRemove = (file: any, fileList: any[]) => {
  // 处理文件移除
}

// 文件上传前检查
const beforeUpload = (file: any) => {
  const allowedTypes = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf', 'text/plain']
  const isAllowedType = allowedTypes.includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isAllowedType) {
    ElMessage.error('只能上传 doc/docx/pdf/txt 格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return false // 阻止自动上传
}

// 显示关键词输入框
const showKeywordInput = () => {
  keywordInputVisible.value = true
  nextTick(() => {
    keywordInputRef.value?.focus()
  })
}

// 添加关键词
const handleAddKeyword = () => {
  const keyword = keywordInputValue.value.trim()
  if (keyword && !formData.keywords.includes(keyword)) {
    formData.keywords.push(keyword)
  }
  keywordInputVisible.value = false
  keywordInputValue.value = ''
}

// 移除关键词
const handleRemoveKeyword = (keyword: string) => {
  const index = formData.keywords.indexOf(keyword)
  if (index > -1) {
    formData.keywords.splice(index, 1)
  }
}

// 保存草稿
const handleSaveDraft = async () => {
  try {
    // 基础验证
    await formRef.value.validateField(['name', 'code', 'type', 'department'])
    
    const submitData = {
      ...formData,
      status: 'draft'
    }
    
    // 模拟保存API
    await mockSaveSystem(submitData)
    
    ElMessage.success('草稿保存成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('保存草稿失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    // 数据预处理
    const submitData = {
      ...formData,
      keywords: formData.keywords || [],
      createTime: isEdit.value ? formData.createTime : new Date().toLocaleString(),
      updateTime: new Date().toLocaleString(),
      id: isEdit.value ? formData.id : Date.now() // 模拟生成ID
    }
    
    // 模拟API调用
    await mockSaveSystem(submitData)
    
    ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    emit('success', submitData)
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('表单验证失败，请检查输入内容')
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 模拟API函数
const mockSaveSystem = (data: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('保存制度数据:', data)
      resolve({ success: true })
    }, 1000)
  })
}
</script>

<style scoped>
.system-form {
  padding: 0 20px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  resize: vertical;
}

:deep(.el-tag) {
  margin-right: 8px;
  margin-bottom: 8px;
}
</style>